<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;

use app\common\controller\Smscm;
use app\common\model\Users;
use app\api\validate\User as UserValidate;
use app\common\service\EngineerService;
use think\Exception;
use think\Db;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Register extends Auth
{
    public $noNeedLogin = ['login','index','findPassword'];

    /**
     * 账号密码登录
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['phone']) || empty($getData['password'])) {
                $this->result('缺少必要的参数', '', 204);
            }
            $userModel = new Users();
            $code = $userModel->checkUser($getData);
            switch ($code) {
                case 2000;
                    $token = token_rand();
                    Users::where(['phone'=>$getData['phone'],'group'=>'2'])->update(['app_token'=>$token]);
                    $userInfo = Users::where(['phone'=>$getData['phone'],'group'=>'2'])->field('id,phone,real_name,app_token,avatar,store_id')->find();
                    unset($userInfo->password);
                    unset($userInfo->safeword);
                    $storeInfo = Db::name('qt_store')->field('start_time,end_time')->where(['id'=>$userInfo['store_id']])->find();
                    $userInfo['start_time'] = $storeInfo['start_time'];
                    $userInfo['end_time'] = $storeInfo['end_time'];
                    $userInfo['login_token'] = $token;
                    $this->result('登录成功', $userInfo, 200);
                    break;
                case 10001;
                    $this->result('用户不存在，请先去注册', '', 205);
                    break;
                case 10002;
                    $this->result('账户被禁用，请联系客服', '', 206);
                    break;
                case 10003;
                    $this->result('账号密码错误', '', 207);
                    break;
            }

        }
        $this->result('无效的请求', '', 204);

    }

    /**
     * 用户注册或者登录
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $userInfo = Users::where(['phone' => $getData['phone'],'group'=>'2'])->find();
            if (empty($userInfo)) {
                //检测短信验证码
                $sms = new Smscm();
                $checkPhone = $sms->check_smscode($getData['phone'], $getData['code'], 1);
                if ($checkPhone['code'] == 200) {
                    $find = Db::name('qt_users')->where('phone',$getData['phone'])->find();
                    if(empty($find)){
                        $insertData['phone'] = $getData['phone'];
                        $insertData['create_time'] = time();
                        //插入用户数据，并返回用户ID
                        $insert = Users::create($insertData);
                        $userId = $insert->id;
                        //更新用户信息
                        $up['ivt_code'] = $userId;
                        $up['login_token'] = token_rand();
                        $update = Users::where(['id' => $userId])->update($up);
                        //返回数据结果
                        if ($update) {
                            $data = Users::find($userId);
                            unset($data->password);
                            unset($data->safeword);
                            $this->result('注册成功', $data, 200);
                        }
                    }else{
                        if($find['status'] == '0'){
                            unset($find['password']);
                            unset($find['safeword']);
                            $this->result('登录成功', $find, 200);
                        }
                        $this->result('账户被禁用，请联系客服', '', 204);
                    }

                }
                $this->result('短信验证失败', '', 204);
            }
            if ($userInfo->status == 1) {
                $this->result('账户被禁用，请联系客服', '', 204);
            }else{
                $sms = new Smscm();
                $checkPhone = $sms->check_smscode($getData['phone'], $getData['code'], 1);
                $find = Db::name('qt_users')->where('phone',$getData['phone'])->find();
                if ($checkPhone['code'] == 200) {
                    unset($find['password']);
                    unset($find['safeword']);
                    $this->result('登录成功', $find, 200);
                }else{
                    $this->result('短信验证失败', '', 204);
                }
            }
        }
    }


    /**
     * 找回密码
     */
    public function findPassword()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('update')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $userId = Users::where('phone', $getData['phone'])->value('id');
            if (empty($userId)) {
                $this->result('当前手机号暂未注册', '', 204);
            }
            if ($getData['password'] == $getData['new_password']) {
                $sms = new Smscm();
                $checkPhone = $sms->check_smscode($getData['phone'], $getData['code'], 2);
                if ($checkPhone['code'] == 200) {
                    $newPassword = pwd($getData['password'], $userId);
                    $update = Users::where('id', $userId)->update(['password' => $newPassword]);
                    if ($update) {
                        $this->result('密码修改成功', '', 200);
                    }
                }
                $this->result('密码修改失败', '', 204);
            }
            $this->result('两次密码不一致', '', 204);
        }
    }

    /**
     * 修改密码
     */
    public function change_pwd(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            //更新登录密码
            $validate = new UserValidate();
            if (!$validate->scene('changePwd')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $pass = pwd($getData['old_password'],$userInfo['id']);
            $userRes = Db::name('qt_users')->where(['id'=>$userInfo['id']])->find();
            if($pass == $userRes['password']){
                if($getData['password'] == $getData['new_password']){
                    //更新密码
                    $newPss = pwd($getData['password'],$userInfo['id']);
                    $update = Users::where(['id'=>$userInfo['id']])->update(['password'=>$newPss]);
                    if($update){
                        $this->result('密码更新成功', '', 200);
                    }
                    $this->result('密码更新失败', '', 204);
                }
                $this->result('两次密码不一致', '', 204);
            }
            $this->result('旧密码不正确', '', 204);
        }
    }


    /**
     * 找回密码
     */
    public function save_phone()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['phone']) ||empty($getData['code']) || empty($getData['new_phone'])){
                $this->result('缺少参数', '', 204);
            }
            $userId = Users::where('phone', $getData['phone'])->value('id');
            if (empty($userId)) {
                $this->result('当前用户暂未注册', '', 204);
            }
            $sms = new Smscm();
            $checkPhone = $sms->check_smscode($getData['phone'], $getData['code'], 3);
            if ($checkPhone['code'] == 200) {
                $update = Users::where('id', $userId)->update(['phone' => $getData['new_phone'],'login_token'=>token_rand()]);
                if ($update) {
                    $this->result('手机修改成功', '', 200);
                }
            }
            $this->result('手机修改失败', '', 204);

        }
    }

    /**
     * 添加技师
     */
    public function addEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add_engineer')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $check_work_num = Db::name('qt_users')->where('work_number',$getData['work_number'])->find();
            if (!empty($check_work_num)) {
                $this->result('工号已经存在请修改工号', '', 204);
            }

            try{
                Db::startTrans();
                //处理数据
                $insertData['store_id'] = $this->userInfo['store_id'];
                $insertData['phone'] = $getData['phone'];
                $insertData['work_number'] = $getData['work_number'];
                $insertData['real_name'] = $getData['real_name'];
                $insertData['sex'] = $getData['sex']??0;
                $insertData['age'] = $getData['age']??0;
                $insertData['type_id'] = $getData['type_id'];
                $insertData['top_type_id'] = Db::name('qt_work_type')->where('id', $getData['type_id'])->value('pid');
                $insertData['work_time'] = strtotime($getData['work_time']) ?? null;
                $insertData['overtime'] = $getData['overtime'] ?? 0;
                $insertData['role'] = '3';
                $insertData['group'] = $getData['group_id'];
                $insertData['create_time'] = time();
                $insertData['content'] = $getData['content'] ?? '';
                $insertData['add_clock_project'] = $getData['add_clock_project'] ?? 0;
                $insertData['show_wechat'] = $getData['show_wechat'] ?? 0;
                $insertData['update_project_role'] = $getData['update_project_role'] ?? 0;
                $insertData['hand_code'] = $getData['hand_code'] ?? 0;

                //插入用户数据，并返回用户ID
                $userId = Db::name('qt_users')->insertGetId($insertData);
                //插入权限
                $auth['engineer_id'] = $userId;
                $auth['is_open'] = $getData['is_open'];
                $auth['is_recharge'] = $getData['is_recharge'];
                $auth['is_pay'] = $getData['is_pay'];
                $auth['is_retreat'] = $getData['is_retreat'];
                $auth['is_room'] = $getData['is_room'];
                $auth['is_hand_card'] = $getData['is_hand_card'];
                $auth['is_room_content'] = $getData['is_room_content'];
                Db::name('qt_users_auth')->insert($auth);
                //插入技师服务项目
                $projectIDs = explode(',',$getData['project_ids']);
                foreach ($projectIDs as $key=>$value){
                    $insert[$key]['engineer_id'] = $userId;
                    $insert[$key]['project_id'] = $value;
                    $insert[$key]['create_time'] = time();
                }
                Db::name('qt_user_project')->insertAll($insert);
                //更新用户信息
                $up['ivt_code'] = $userId;
                $up['login_token'] = token_rand();
                $up['password'] = pwd('123456',$userId);
                Users::where(['id' => $userId])->update($up);

                //根据手牌编号更新手牌表员工ID
                if (!empty($getData['hand_code'])) {
                    EngineerService::updateHandCard($getData['hand_code'],$userId);
                }

                //写技师房列表
                $max_sort = Db::name('qt_order_queue')->where(['store_id'=>$this->userInfo['store_id']])->lock(true)->max('sort');
                Db::name('qt_order_queue')->insert([
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$userId,
                    'created_time'=>time(),
                    'sort'=>$max_sort+1,
                ]);

                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('添加失败'.$exception->getMessage(),'',204);
            }
            $this->result('添加成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 添加员工
     */
    public function add_staff(){
     if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add_floor')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }

            $insertData['work_number'] = $getData['work_number'];
            $insertData['real_name'] = $getData['real_name'];
            $insertData['sex'] = $getData['sex'];
            $insertData['post_id'] = $getData['post_id'];
            $insertData['phone'] = $getData['phone'];
            $insertData['card'] = !empty($getData['card']) ? $getData['card'] : '';
            $insertData['work_time'] = strtotime($getData['work_time']);
            $insertData['operation'] = !empty($getData['operation']) ? $getData['operation'] : 1;
            $insertData['create_time'] = time();
            $insertData['group'] = $getData['group_id'];

            try{
                Db::startTrans();
                $userId = Db::name('qt_users')->insertGetId($insertData);
                //更新用户信息
                $up['ivt_code'] = $userId;
                $up['login_token'] = token_rand();
                Db::name('qt_users')->where(['id' => $userId])->update($up);

                //根据手牌编号更新手牌表员工ID
                //if (!empty($getData['hand_code'])) {
                //    EngineerService::updateHandCard($getData['hand_code'],$userId);
                //}

                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('添加失败'.$exception->getMessage(),'',204);
            }
            $this->result('添加成功','',200);
        }
    }



    // 用于请求微信接口获取数据
    public function get_by_curl($url, $post = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * 添加工种
     */
    public function add_type(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $insertData['store_id'] = $this->store_id;
            $insertData['title'] = $getData['title'];
            $insertData['pid'] = $getData['pid'];
            $insertData['sort'] = $getData['sort'];
            $insertData['created_time'] = time();
            $insert = Db::name('qt_work_type')->insert($insertData);
            if($insert){
                $this->result('添加成功','',200);
            }
            $this->result('添加失败','',204);
        }
        $this->result('无效的请求', '', 204);
    }

}
